package net.csiit.tools.fileserver.client.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author adam
 * @date 2021-12-13
 */
@Slf4j
public class RestTemplateCreator {

    public static RestTemplate restTemplate() {
        return restTemplate(70, 70);
    }

    public static RestTemplate restTemplate(int readTimeoutSeconds, int connectTimeoutSeconds) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });

        try {
            TrustManager[] trustManagers = new TrustManager[] { new HTTPSTrustManager() };
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//        NoRedirectClientHttpRequestFactory factory = new NoRedirectClientHttpRequestFactory();
        factory.setReadTimeout((int) TimeUnit.SECONDS.toMillis(readTimeoutSeconds));
        factory.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(connectTimeoutSeconds));

        return new RestTemplate(factory);
    }

}
